//
//  YWDoTempTroubleMissionTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/17.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoTempTroubleMissionTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"

//#import "YWTextFieldCell.h"
#import "YWRepairCostsCell.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"
#import "YWWriteRuntimeCell.h"
#import "YWDropDownRunTimeCell.h"

#import "DropDownListViewController.h"
//#import "YWImageView.h"
#import "YWPhotoView.h"
//#import "YWAlertView.h"
#import "MBProgressHUD.h"

#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWEquipmentType.h"
#import "YWResourceManager.h"
#import "YWNotifyManager.h"
#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWHandler.h"
#import "YWEquipmentFieldRecord.h"
#import "YWTroubleMissionModel.h"
#import "YWReportTroubleModel.h"
#import "YWLocation.h"
#import "YWBuildingManager.h"
#import "YWTroubleMissionManager.h"

@interface YWDoTempTroubleMissionTableViewController ()<YWTakePhotoCellDelegate,DropDownListDelegate,YWRepairCostsCellDelegate,YWWriteNoteCellDelegate>
@property (nonatomic, strong) YWEquipment *currentEquipment;
@property (nonatomic, strong) NSArray *allEquipments;
@property (nonatomic, strong) UIView *footView;

@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, assign) NSInteger reasonId;
@property (nonatomic, copy) NSString *reasonName;
//@property (nonatomic, copy) NSString *changeParts;
@property (nonatomic, strong) NSMutableArray *replacements;//配件数组
@property (nonatomic, copy) NSString *cost;
@property (nonatomic, copy) NSString *material;
@property (nonatomic, copy) NSString *note;
//扫描进入任务页面时的时间
@property (nonatomic, assign) NSTimeInterval clientScanTime;

@end

@implementation YWDoTempTroubleMissionTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"trouble", nil);//@"维修";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    _reasonId = 0;
    _reasonName = NSLocalizedString(@"environment", nil);//@"环境";
    _clientScanTime = [[NSDate date] timeIntervalSince1970]*1000;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    
    [self.tableView registerClass:[YWRepairCostsCell class] forCellReuseIdentifier:YWRepairCostsCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    [self.tableView registerClass:[YWWriteRuntimeCell class] forCellReuseIdentifier:YWWriteRuntimeCellIdentifier];
    [self.tableView registerClass:[YWDropDownRunTimeCell class] forCellReuseIdentifier:YWDropDownRunTimeCellIdentifier];
}
//- (void)showTipsWhenFirstEnter{
//    BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:KNotFirstEnterMaintenance] boolValue];
//    if (!notFirstEnter) {
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:KFirstEnterMaintenance preferredStyle:UIAlertControllerStyleAlert];
//        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
//        [alert addAction:[UIAlertAction actionWithTitle:@"不再提示" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNotFirstEnterMaintenance];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }]];
//        [self presentViewController:alert animated:YES completion:nil];
//    }
//}

- (void)setTroubleMissionModel:(YWTroubleMissionModel *)troubleMissionModel{
    _troubleMissionModel = troubleMissionModel;
    _allEquipments = nil;
    if (self.allEquArray) {
        _allEquipments = self.allEquArray;
    }else if (_troubleMissionModel.trouble.qrcodeId) {
        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_troubleMissionModel.trouble.qrcodeId];
    }else if (_troubleMissionModel.trouble.location.locationId){
        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithLocationId:_troubleMissionModel.trouble.location.locationId];
    }
    
    [_allEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        if (_troubleMissionModel.trouble.equipment.equipmentId && [_troubleMissionModel.trouble.equipment.equipmentId isEqualToString:equipment.equipmentId]) {
            _currentEquipment = equipment;
        }
        NSArray *customProperty = [[YWEquipmentManager shareManager] equipmentFieldsWithTypeId:equipment.equipmentTypeId maintenanceTypeId:YWMaintenanceTypeTrouble];
        equipment.runTimeParameterArray = customProperty.count?customProperty:nil;
    }];
    if (_currentEquipment==nil && _allEquipments.count>0) {
        _currentEquipment = _allEquipments[0];
    }
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 4) {
        return _currentEquipment.runTimeParameterArray.count?75:44;
    }else if (indexPath.section == 6){
        CGFloat imageH = YWPhotoSize*(_currentEquipment.totalImageNameArray.count/4+1) + YWPhotoGap*(_currentEquipment.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }else if (indexPath.section == 5){
        return 90;
    }else{
        return 44;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 7;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _allEquipments.count;
    }else if (section==4){
        return [_currentEquipment.runTimeParameterArray count]>0?[_currentEquipment.runTimeParameterArray count]:1;
    }else if (section == 2){
        return [_replacements count] + 1;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"YWDoTroubleMissionTableViewControllerIdentifier";
    UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (myCell == nil) {
        myCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        myCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section==0 || indexPath.section==1) {
        if (indexPath.section == 0) {
            YWEquipment *equipment = _allEquipments[indexPath.row];
            myCell.textLabel.text = equipment.equipmentName;
            if ([equipment.equipmentId isEqualToString:_currentEquipment.equipmentId]) {
                myCell.accessoryType = UITableViewCellAccessoryCheckmark;
            }else{
                myCell.accessoryType = UITableViewCellAccessoryNone;
            }
            
        }else{
            myCell.textLabel.text = _reasonName;
            myCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return myCell;
    }else if (indexPath.section==2){
        myCell.textLabel.textColor = [UIColor blackColor];
        if (indexPath.row==0) {
            myCell.textLabel.text = NSLocalizedString(@"addAccessories", nil);//@"添加配件";
            myCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return myCell;
        }else{
            myCell.textLabel.text = [NSString stringWithFormat:@"%ld.%@",(long)indexPath.row,_replacements[indexPath.row-1]];
            myCell.accessoryType = UITableViewCellAccessoryNone;
            return myCell;
        }
    }else if (indexPath.section==3){
        YWRepairCostsCell *cell = [tableView dequeueReusableCellWithIdentifier:YWRepairCostsCellIdentifier];
        cell.delegate = self;
        return cell;
    }else if (indexPath.section==4){
        YWRunTimeParameter *runTimeParameter = _currentEquipment.runTimeParameterArray.count ? _currentEquipment.runTimeParameterArray[indexPath.row]:nil;
        if (runTimeParameter.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
            YWDropDownRunTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDropDownRunTimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }else{
            YWWriteRuntimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteRuntimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }
        
    }else if (indexPath.section==5){
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.section==6){
        YWTakePhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.delegate = self;
        cell.totalImageNameArray = _currentEquipment.totalImageNameArray;
        return cell;
    }
    
    return [[UITableViewCell alloc] init];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && [self.replacements count]>0 && indexPath.row>0) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2 && [self.replacements count]>0 && indexPath.row>0) {
        [self.replacements removeObjectAtIndex:indexPath.row-1];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWDoTroubleMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else if (section==1){
        return NSLocalizedString(@"selectTroubleReason", nil);//@"选择故障原因";
    }else if (section==2){
        return NSLocalizedString(@"changeAccessories", nil);//@"更换配件";
    }else if (section==3){
        return NSLocalizedString(@"expenses", nil);//@"费用";
    }else if (section==4){
        return NSLocalizedString(@"runtimeParameter", nil);//@"运行参数";
    }else if (section==5){
        return NSLocalizedString(@"note", nil);//@"备注";
    }else if (section==6){
        return NSLocalizedString(@"takePhotoToUpload", nil);//@"拍照上传";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWEquipment *equipment = self.allEquipments[indexPath.row];
        _currentEquipment = equipment;
        self.troubleMissionModel.trouble.equipment = _currentEquipment;
        [self.tableView  reloadData];
    }else if (indexPath.section ==1){
        DropDownListViewController *selectReasonVC = [[DropDownListViewController alloc] init];
        selectReasonVC.delegate = self;
        selectReasonVC.currentIndex = _reasonId;
        [self.navigationController pushViewController:selectReasonVC animated:YES];
    }else if (indexPath.section == 2 && indexPath.row==0){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"addAccessories", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.placeholder = NSLocalizedString(@"writeTheNameOfAccessories", nil);//@"填写配件名称";
        }];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UITextField *textField = alert.textFields.firstObject;
            NSString *replaceName = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if ([YWCommonTool isContainsEmoji:replaceName]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
            }else if (replaceName.length==0){
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleChangePartsNotNull, nil)];
            }else if (replaceName.length>100){
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleChangePartsMax, nil)];
            }else{
                [self.replacements addObject:replaceName];
                [self.tableView reloadData];
            }
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - YWTakePhotoCellDelegate
- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    _currentEquipment.totalImageNameArray = arr;
    
    [self.tableView reloadData];
}

#pragma mark - DropDownListDelegate
- (void)selectValue:(NSInteger)reasonId andContent:(NSString *)content{
    _reasonId = reasonId;
    _reasonName = content;
    [self.tableView reloadData];
}

#pragma mark - YWRepairCostsCellDelegate
- (void)passRepairCosts:(NSString *)laborCost materialCost:(NSString *)materialCost{
    if (laborCost.length) {
        _cost = laborCost;
    }
    if (materialCost.length) {
        _material = materialCost;
    }
}
#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    _note = note;
}
- (void)clickCommitButton:(id)sender{
    [self.view endEditing:YES];
    if ([_cost floatValue]<0 || [_material floatValue]<0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"expensesMustBeMoreThanZero", nil)];
        return;
    }
    
    if (_note.length == 0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleDescriptionNotNull, nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:_note]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_note.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleDescriptionMax, nil)];
        return;
    }
    
    __block BOOL isRequire = YES;
    __block NSString *reasonable = nil;
    __block BOOL containEmoji = NO;
    [_currentEquipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull stop) {
        if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
            isRequire = NO;
            *stop = YES;
        }
        if (field.fieldType.fieldTypeId==YWEquipmentFieldTypeIdNumber && (field.maxFieldValue!=0 || field.minFieldValue!=0) && field.fieldValue.length>0 && ([field.fieldValue integerValue]>field.maxFieldValue||[field.fieldValue integerValue]<field.minFieldValue)) {
            reasonable = field.fieldName;
            //*stop = YES;
        }
        if ([YWCommonTool isContainsEmoji:field.fieldValue]){
            containEmoji = YES;
            *stop = YES;
        }
    }];
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (reasonable.length>0) {
        NSString *tips = [NSString stringWithFormat:@"%@%@",reasonable,NSLocalizedString(@"valueNotInReasonableRangeAndMakeSureToCommit", nil)];
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tips preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self commitRecord];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self commitRecord];
    }
}
- (void)commitRecord{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(kTextConfirmSubmitMission, nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        _troubleMissionModel.trouble.equipment = _currentEquipment;
        YWLocation * location = [[YWBuildingManager shareManager] locationWithId:_currentEquipment.locationId];
        _troubleMissionModel.trouble.location = location;
       NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970] * 1000;
        _troubleMissionModel.troubleStatus = YWTroubleMissionStatusFinish;
        YWHandler *mySelf = [[YWHandler alloc]init];
        YWLoginUser *user = [YWLoginTool loginUser];
        mySelf.uniqueId = user.uniqueId;
        mySelf.userName = user.userName;
        mySelf.headIcon = user.headIcon;
        mySelf.mobile = user.mobile;
        _troubleMissionModel.executor = mySelf;
        _troubleMissionModel.creator = mySelf;
        _troubleMissionModel.trouble.reporter = nil;
        _troubleMissionModel.trouble.reportTime = currentTime;
        _troubleMissionModel.createTime = currentTime;
        _troubleMissionModel.updateTime = currentTime;
        _troubleMissionModel.cutoffTime = currentTime;
        _troubleMissionModel.read = YES;
        
        __block YWEquipmentTroubleRecord* troubleRecord = [self createEquipmentTroubleRecord];
        __block NSArray* pictures = [self createPicturesWithTroubleRecord:troubleRecord];
        __block NSArray *equipmentFieldRecords = [self createEquipmentFieldsRecordsWithTroubleRecords:troubleRecord];
        
        
        BOOL saveMission = [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:_troubleMissionModel?@[_troubleMissionModel]:nil needUpdateReportTrouble:YES];
        BOOL saveTroubleRecord = [[YWTroubleMissionManager shareManager] updateTroubleRecord:troubleRecord];
        BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
        BOOL saveEquipmetFieldRecord = [[YWMissionManager shareManager] updateEquipmentFieldRecords:equipmentFieldRecords];
        
        if (saveMission && saveTroubleRecord && savePicturesToDB && saveEquipmetFieldRecord && troubleRecord) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCommitSuccess, nil)];
        
            //上传
            [[YWTroubleMissionManager shareManager] startUploadTroubleMissionRecords:@[troubleRecord] troubleMissionModel:_troubleMissionModel pictures:pictures];
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        else {
            [self.HUD hide:YES];
            YWLog(@"保存数据库失败");
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitTaskFail, nil)];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSArray*)createPicturesWithTroubleRecord:(YWEquipmentTroubleRecord*)troubleRecord
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [_currentEquipment.totalImageNameArray count]; i++) {
        YWPicture* picture = [[YWPicture alloc] init];
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = _currentEquipment.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureUploadStatusNull;
        picture.missionId = _troubleMissionModel.trouble.troubleId;
        picture.maintenanceType = YWMaintenanceTypeTrouble;
        picture.equipmentId = _troubleMissionModel.trouble.equipment.equipmentId;
        picture.pictureTroubleType = YWPictureTroubleTypeRecord;
        picture.recordId = troubleRecord.recordId;
        [pictures addObject:picture];
    }
    return pictures;
}

- (YWEquipmentTroubleRecord*)createEquipmentTroubleRecord
{
    YWEquipmentTroubleRecord* troubleRecord = [[YWEquipmentTroubleRecord alloc] init];
    troubleRecord.recordId = [YWCommonTool randNumber];
    /**任务ID*/
    troubleRecord.missionId = _troubleMissionModel.trouble.troubleId;
    NSString *uniqueTag = [YWCommonTool randStringId];//[NSString stringWithFormat:@"%ld",(long)troubleRecord.recordId] ;
    troubleRecord.uniqueTag = uniqueTag;
    troubleRecord.equipmentId = _troubleMissionModel.trouble.equipment.equipmentId;
    troubleRecord.note = _note;
    troubleRecord.completeTime = [[NSDate date] timeIntervalSince1970] * 1000;
    troubleRecord.clientScanTime = _clientScanTime;
    troubleRecord.handlerName = [YWLoginTool loginUser].userName;
    troubleRecord.reasonId = _reasonId;
    troubleRecord.replacementStatus = _replacements.count==0?YWRecordReplacementStatusNO:YWRecordReplacementStatusYES;
    troubleRecord.replacements = _replacements;
    __block NSString *replacementName = @"";
    [_replacements enumerateObjectsUsingBlock:^(NSString*  _Nonnull replaceN, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx>0) {
            replacementName = [replacementName stringByAppendingString:@","];
        }
        replacementName = [replacementName stringByAppendingString:replaceN];
    }];
    troubleRecord.replacementName = replacementName;
    ;
    troubleRecord.recordType = YWMalfunctionRecordTypeFixed;
    troubleRecord.uploadStatus = YWEquipmentMaintenanceRecordUploadStatusUploading;
    troubleRecord.equipmentTypeId = _currentEquipment.equipmentTypeId;
    
    troubleRecord.reporterName = _troubleMissionModel.trouble.reporter.userName;
    troubleRecord.reporterNumber = _troubleMissionModel.trouble.reporter.mobile;
    troubleRecord.reportNote = _troubleMissionModel.trouble.note;
    troubleRecord.reportTime = _troubleMissionModel.trouble.reportTime;
    troubleRecord.maintenanceTypeId = YWMaintenanceTypeTrouble;
    
    NSString *dayMonthString = [YWCommonTool showTime:troubleRecord.completeTime / 1000 andFormatter:KTimeFormatDayMonth];
    troubleRecord.dayMonthString = dayMonthString;
    troubleRecord.laborCosts = _cost;
    troubleRecord.materialCosts = _material;
    return troubleRecord;
}
- (NSArray*)createEquipmentFieldsRecordsWithTroubleRecords:(YWEquipmentTroubleRecord*)troublerecord{
    
    __block NSMutableArray* fieldsArray = nil;
    if ([troublerecord.equipmentId isEqualToString:_currentEquipment.equipmentId]) {
        fieldsArray = [[NSMutableArray alloc]init];
        
        [_currentEquipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull equStop) {
            YWEquipmentFieldRecord *fieldRecord = [[YWEquipmentFieldRecord alloc]init];
            fieldRecord.uniqueTag = troublerecord.uniqueTag;
            fieldRecord.fieldId = field.fieldId;
            fieldRecord.fieldName = field.fieldName;
            if (field.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                fieldRecord.fieldTypeId = YWEquipmentFieldTypeIdDownSelect;
                fieldRecord.fieldOption = field.fieldOptionValue;
            }else{
                fieldRecord.fieldValue = field.fieldValue;
            }
            fieldRecord.maintenanceTypeId = YWMaintenanceTypeTrouble;
            [fieldsArray addObject:fieldRecord];
            
        }];
        troublerecord.equipmentFieldRecord = fieldsArray;
    }
    
    return fieldsArray;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"commit", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickCommitButton:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
        
    }
    return _footView;
}
- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (NSMutableArray *)replacements{
    if (!_replacements) {
        _replacements = [NSMutableArray array];
    }
    return _replacements;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
